package activities;

import java.io.IOException;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.searchparking.R;

import com.searchparking.BUS.DataSingleton;
import com.searchparking.BUS.RestfulWSHelper;

import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements OnClickListener,
		LocationListener {
	private ImageView img_about, img_parking;
	protected LocationManager locationManager;
	protected LocationListener locationListener;
	protected Context context;
	private TextView txtLocation;
	public static String address;
	String lat;
	String provider;
	public static Double latitude, longitude;
	protected boolean gps_enabled, network_enabled;
	protected Location location;
	GoogleMap googleMap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		init();
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
//		//
		 int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

	        // Showing status
	        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
	        	
	        	int requestCode = 10;
	            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
	            dialog.show();
	            
	        }else {	// Google Play Services are available	
			
				
				 // Getting LocationManager object from System Service LOCATION_SERVICE
		        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		
		        // Creating a criteria object to retrieve provider
		        Criteria criteria = new Criteria();
		
		        // Getting the name of the best provider
		        String provider = locationManager.getBestProvider(criteria, true);
		
		        // Getting Current Location
		         location = locationManager.getLastKnownLocation(provider);
        
     // Getting latitude of the current location
     		this.latitude = location.getLatitude();
     		
     		// Getting longitude of the current location
     		this.longitude = location.getLongitude();		
       // getting address current
        try {

            Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());
            List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
            if (addresses.isEmpty()) {
                txtLocation.setText("Waiting for Location");
            }
            else {
                if (addresses.size() > 0) {
                	txtLocation.setText(  addresses.get(0).getAddressLine(0) +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
                	address = addresses.get(0).getAddressLine(0) +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName();
                	
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace(); // getFromLocation() may sometimes fail
        }
	        }
        
		/*
		 * NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null
		 * && netInfo.isConnectedOrConnecting()) { Log.d("Connect","OK"); }
		 * else{ Log.d("Connect","NoOK"); }
		 */
		RestfulWSHelper jsonHelper = new RestfulWSHelper();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// JSONObject dataJson =
		// jsonHelper.doGet("http://haipt.w.pw/service.php?action=getAllParking");
		//String json = "[{\"ParkId\":\"Park01\",\"Address\":null,\"ParkName\":\"Parking1\",\"Latitude\":\"16.072919681829728108\",\"Longtitude\":\"128.21044073650523\",\"Status\":\"10\"},{\"ParkId\":\"Park0\",\"Address\":null,\"ParkName\":\"Parking1\",\"Latitude\":\"108.21044073650523\",\"Longtitude\":\"16.072919681829128108\",\"Status\":\"10\"},{\"ParkId\":\"Park03\",\"Address\":null,\"ParkName\":\"Parking2\",\"Latitude\":\"308.214392\",\"Longtitude\":\"16.071677\",\"Status\":\"10\"}]";
		String json = "[{\"ParkId\":\"Park01\",\"Address\":\" 46 Tran cao Van\",\"ParkName\":\"Parking1\",\"Latitude\":\"16.07298981829728108\",\"Longtitude\":\"103.21044073650523\",\"Status\":\"10\"},{\"ParkId\":\"Park0\",\"Address\":\"32 Le duan\",\"ParkName\":\"Parking1\",\"Latitude\":\"16.039379\",\"Longtitude\":\"108.168442\",\"Status\":\"10\"},{\"ParkId\":\"Park03\",\"Address\":\"52 Bach Dang\",\"ParkName\":\"Parking2\",\"Latitude\":\"20.214392\",\"Longtitude\":\"140.071677\",\"Status\":\"10\"}]";
		try {
			json = DataSingleton.converJsonFormat(json);
			JSONObject dataJson = new JSONObject(json);
			DataSingleton.setData(dataJson);
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		setOnclick();
	}

	public void init() {
		img_about = (ImageView) findViewById(R.id.img_about);
		img_parking = (ImageView) findViewById(R.id.img_parking);
		txtLocation = (TextView) findViewById(R.id.txt_location);

	}

	public void setOnclick() {
		img_about.setOnClickListener(this);
		img_parking.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.img_about:

			Intent intent_about = new Intent(this, AboutActivity.class);
			startActivity(intent_about);

			break;
		case R.id.img_parking:
			Bundle bundle = new Bundle();
			bundle.putDouble("latitude", this.latitude);
			bundle.putDouble("longitude", this.longitude);
			Intent intent_parking = new Intent(this, ResultSearchActivity.class);
			intent_parking.putExtras(bundle);
			startActivity(intent_parking);

			break;
		default:
			break;
		}

	}

	@Override
	public void onLocationChanged(Location location) {

		Log.d("VITRI", "Latitude:" + location.getLatitude() + ", Longitude:"
				+ location.getLongitude());
		this.latitude = location.getLatitude();
		this.longitude = location.getLongitude();
	}

	@Override
	public void onProviderDisabled(String provider) {
		Log.d("Latitude", "disable");
	}

	@Override
	public void onProviderEnabled(String provider) {
		Log.d("Latitude", "enable");
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		Log.d("Latitude", "status");
	}
}
